package dongshi.daddy.huohuo;

import java.util.concurrent.TimeUnit;

class VolatileExample {
    int x = 0;
    /*volatile*/ boolean v = false;

    public void writer() {
        x = 42;
        v = true;
    }

    public void reader() {
        if (v == true) {
            // 这里x会是多少呢？
            System.out.println(x);
        }
    }

    public static void main(String[] args) {
        VolatileExample volatileExample = new VolatileExample();

        new Thread(() -> {
            System.out.println(volatileExample.x);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            volatileExample.reader();
        }).start();


        new Thread(() -> {
//          try {
//            TimeUnit.SECONDS.sleep(1);
//          } catch (InterruptedException e) {
//            e.printStackTrace();
//          }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            volatileExample.writer();
        }).start();


    }
}
